﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.Data;
using System.Windows.Media.Imaging;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Controls;
using System.Globalization;
using produccion.modelo;
using produccion.AccesoDatos;
using produccion.clases;
using System.Windows.Input;
using System.Collections.Specialized;

namespace produccion.vistamodelo
{
    class VMMantenimientodeCausas : ViewModelBase
    {
        #region Campos

            private List<CLSTABCAU> _liscausa = new List<CLSTABCAU>();
            private ProcesoProduccionRepositorio _repositorio = new ProcesoProduccionRepositorio();

        #endregion

        #region constructor

            public VMMantenimientodeCausas()
            {
                try
                {
                    consultarCausas();
                    liscausas.CollectionChanged += OnCollectionChanged;

                    if (MDOgeneral.conexion == null || MDOgeneral.conexion.State == ConnectionState.Closed)
                    {
                        MDOgeneral.conectar();
                    }
                    strTituloVentana = "Mantenimiento de causas - Usuario: " + MDOgeneral.usuario + " - [FRMMantenimientodeCausas]";
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

        #endregion

        #region Interfaces publicas

            private string _strTituloVentana;
            public string strTituloVentana
            {
                get { return _strTituloVentana; }
                set { _strTituloVentana = value; base.OnPropertyChanged("strTituloVentana"); }
            }

            public List<CLSTABCAU> liscausa
            {
                get { return _liscausa; }
                set { _liscausa = value; base.OnPropertyChanged("liscausa"); }
            }

            private MDOgeneral.mensaje _msn = new MDOgeneral.mensaje();
            public MDOgeneral.mensaje msn
            {
                get { return _msn; }
                set { _msn = value; base.OnPropertyChanged("msn"); }
            }

            private ObservableCollection<VMCausas> _liscausas = new ObservableCollection<VMCausas>();
            public ObservableCollection<VMCausas> liscausas
            {
                get { return _liscausas; }
                set { _liscausas = value; base.OnPropertyChanged("liscausas"); }
            }

            private VMCausas _selcausa;
            public VMCausas selcausa
            {
                get { return _selcausa; }
                set { _selcausa = value; base.OnPropertyChanged("selcausa"); }
            }

            private Boolean _logValido;
            public Boolean logValido
            {
                get { return _logValido; }
                set { _logValido = value; base.OnPropertyChanged("logValido"); }
            }

        #endregion

        #region Comandos

            RelayCommand _cmdSalir;
            public ICommand cmdSalir
            {
                get
                {
                    if (_cmdSalir == null)
                    {
                        _cmdSalir = new RelayCommand(Salir);
                    }
                    return _cmdSalir;
                }
            }

            RelayCommand _cmdEliminar;
            public ICommand cmdEliminar
            { 
                get
                {
                    if (_cmdEliminar == null)
                    {
                        _cmdEliminar = new RelayCommand(r => eliminarCausa());
                    }
                    return _cmdEliminar;
                }
            }

            RelayCommand _cmdGrabar;
            public ICommand cmdGrabar
            {
                get
                {
                    if (_cmdGrabar == null)
                    {
                        _cmdGrabar = new RelayCommand(r => grabarCausa());
                    }
                    return _cmdGrabar;
                }
            }

        #endregion

        #region Metodos
            
            public void consultarCausas()
            {
                try
                {
                    liscausa = _repositorio.consultarCausas();
                    List<VMCausas> all = (from cau in liscausa select new VMCausas(cau)).ToList();
                    foreach (VMCausas cau in all)
                    {
                        cau.validarCausa += validaCausa;
                        cau.PropertyChanged += OnPropertyChanged;
                    }

                    liscausas = new ObservableCollection<VMCausas>(all);
                    liscausas.CollectionChanged += OnCollectionChanged;
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                logValido = ((from cau in liscausas where cau.IsValid.Equals(false) select cau.IsValid).ToList().Count()) > 0 ? true : false;
            }

            void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                try
                {
                    if (e.NewItems != null && e.NewItems.Count > 0)
                    {
                        foreach (VMCausas cau in e.NewItems)
                        {
                            cau.validarCausa += validaCausa;
                            cau.PropertyChanged += OnPropertyChanged;
                        }
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            public string validaCausa(string strCodigoCausa)
            {
                try
                {
                    int i = (from cau in liscausas where cau.codcau_cau.Trim().Equals(strCodigoCausa.Trim()) select cau).ToList().Count();
                    if (i > 1)
                    {
                        return "Código de Causa ya existe";
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                return null;
            }

            private void grabarCausa()
            {
                try
                {
                    List<CLSTABCAU> lstAgregar = (from cau in liscausas where cau.agregar.Equals(true) select cau.getCausas()).ToList();
                    List<CLSTABCAU> lstActualizar = (from cau in liscausas where cau.actualizar.Equals(true) select cau.getCausas()).ToList();
                    List<CLSTABCAU> lstEliminar = (from cau in liscausas where cau.eliminar.Equals(true) select cau.getCausas()).ToList();

                    if (_repositorio.guardarCausas(lstActualizar, lstEliminar, lstAgregar))
                    {
                        msn.texto = "La información de causas fue guardada exitosamente.";
                        msn.tipo = true;
                        consultarCausas();
                    }
                    else
                    {
                        msn.texto = "La información de causas no se pudo grabar.";
                        msn.tipo = false;
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            private void eliminarCausa()
            {
                try
                {
                    if (selcausa.agregar)
                        liscausas.Remove(selcausa);
                    else
                        selcausa.eliminar = !selcausa.eliminar;
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            public void Salir(Object frmformulario)
            {
                ((Window)frmformulario).Close();
            }

        #endregion

        #region Vistas-Modelo

            public class VMCausas : ViewModelBase, IDataErrorInfo
            {

                #region Campos
            
                    private CLSTABCAU _causas = new CLSTABCAU();
                    public delegate string validarCodigoCausa(string codcau_cau);

                #endregion

                #region Constructor
                
                    public VMCausas(CLSTABCAU causas)
                    {
                        _causas = causas;
                    }

                    public VMCausas()
                    {
                        agregar = true;
                        base.OnPropertyChanged("codcau_cau");
                       
                    }
                #endregion

                #region Metodos

                    public CLSTABCAU getCausas()
                    {
                        return _causas;
                    }

                #endregion

                #region Interfaces Publicas

                    public validarCodigoCausa validarCausa;

                    public string codcau_cau
                    {
                        get { return _causas.CODCAU_CAU; }
                        set 
                        {
                            if (agregar == true)
                            {
                                _causas.CODCAU_CAU = value;
                                base.OnPropertyChanged("codcau_cau");
                            }
                        }
                    }

                    public string nombre_cau
                    {
                        get { return _causas.NOMBRE_CAU; }
                        set 
                        {
                            if (_causas.NOMBRE_CAU != value && agregar == false)
                                actualizar = true;
                            _causas.NOMBRE_CAU = value;
                            base.OnPropertyChanged("nombre_cau");
                        }
                    }

                    private bool _actualizar = false;
                    public bool actualizar
                    {
                        get { return _actualizar; }
                        set { _actualizar = value; base.OnPropertyChanged("actualizar"); 
                        }
                    }

                    private bool _eliminar = false;
                    public bool eliminar
                    {
                        get { return _eliminar; }
                        set { _eliminar = value; base.OnPropertyChanged("eliminar"); }
                    }

                    private bool _agregar = false;
                    public bool agregar
                    {
                        get { return _agregar; }
                        set { _agregar = value; base.OnPropertyChanged("agregar"); }
                    }
   
                #endregion

                #region IDataErrorInfo Members

                    string IDataErrorInfo.Error { get { return null; } }

                    string IDataErrorInfo.this[string propertyName]
                    {
                        get { return this.GetValidationError(propertyName); }
                    }

                #endregion

                #region Validation

                    /// <summary>
                    /// Returns true if this object has no validation errors.
                    /// </summary>
                    /// 

                    public bool IsValid
                    {
                        get
                        {
                            foreach (string property in ValidatedProperties)
                                if (GetValidationError(property) != null)
                                    return false;
                            return true;
                        }
                    }

                    static readonly string[] ValidatedProperties = 
                    { 
                        "codcau_cau",
                        "nombre_cau"
                    };

                    string GetValidationError(string propertyName)
                    {
                        if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
                            return null;

                        string error = null;

                        switch (propertyName)
                        {
                            case "codcau_cau":
                                error = this.Validatecodigo();
                                break;
                            case "nombre_cau":
                                error = this.ValidateNombre();
                                break;
                            default:
                                Debug.Fail("Unexpected property being validated on Customer: " + propertyName);
                                break;
                        }
                        return error;
                    }

                    string Validatecodigo()
                    {
                        try
                        {
                            if (codcau_cau == null) { return "Debe ingresar el código de la causa."; }
                            if (codcau_cau != null)
                            {
                                if (codcau_cau.Length > 2) { return "El código de la causa no puede tener mas de 2 caracteres"; }
                                string error = null;
                                error = validarCausa(codcau_cau);
                                

                            }
                            return null;
                        }
                        catch (Exception ex) { MessageBox.Show(ex.Message); }
                        return null;
                    }

                    string ValidateNombre()
                    {
                        try
                        {
                            if (nombre_cau == null) { return "Debe ingresar el nombre de la causa"; }
                            if (nombre_cau != null)
                            {
                                if (nombre_cau.Length > 50) { return "El nombre de la causa no puede tener mas de 50 caracteres"; }
                            }

                            return null;
                        }
                        catch (Exception ex) { MessageBox.Show(ex.Message); }
                        return null;
                    }

                #endregion

            }

        #endregion
    }
}
